"use strict";

// signup controller
app
.controller("SignupFormController", ["$scope", "$http", "$state", "$translate", "AuthService",
                              function($scope,  $http,   $state, $translate,   AuthService) {
		$scope.user = {
			userName : "",
			realName : "",
			password : null,
			email : "",
			mobile_Phone : "",
			verifyKey : "",
			verifyCode : "",
			verifyUrl : ""
		};
		$scope.authError = null;
		$scope.userExists = false; // user not exists
		
		function UserParam(item) {
			var user = {
				userName : item.userName,
				realName : item.realName,
				mobile_Phone : item.mobile_Phone,
				email : item.email,
				password : item.password,
				verifyKey : item.verifyKey,
				verifyCode : item.verifyCode
			};
			return user;
		};

		$scope.signup = function() {
			$scope.authError = null;
			// Try to create
			$http.post(AuthService.getRsContext() + "/rest/user/createUser?" + $.param(UserParam($scope.user)))
				.then(
					function(response) {
						// console.log("SignupFormController
						// response = ",
						// response.data);
						var code = response.data.code;
						if (code == 0) {
							// $scope.user = {};
							 $scope.authError = $translate.instant("user.signupSuccess").location.href("access.login");
							// $state.go('access.signok');
							//$state.go()
						} else {
							$scope.authError = $scope.selectLang == "English" ? response.data.enMessage
									: response.data.message;
						}
						initVerifyCode();
					},
					function(x) {
						$scope.authError = "Server Error";
						initVerifyCode();
					});
		};

		var codeLength = 4;
		var random = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9,
				'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
				'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q',
				'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
		$scope.refreshVerifyCode = function() {
			initVerifyCode();
		};
		var initVerifyCode = function() {
			var codeKey = "";
			for (var i = 0; i < codeLength; i++) {
				var index = Math.floor(Math.random() * 34);
				codeKey += random[index];
			}
			$scope.user.verifyCode = "";
			codeKey = codeKey + (new Date()).getTime();
			$scope.user.verifyKey = codeKey
			$scope.user.verifyUrl = AuthService.getRsContext() + "/rest/verifycode/image?verifyKey=" + codeKey;
		};
		initVerifyCode();
		
		$scope.checkUserExists = function(userName) {
			// check need user name
	    	$http({
	            method: "GET",
	            url: AuthService.getRsContext() + "/rest/user/checkUserName?userName=" + userName
	        }).then(function successCallback(data1) {
	        	if(data1.data.code == 0) {
	        	  $scope.userExists = data1.data.data[0].exists;
	        	}
	        });
		}
	} ]);
